const Excel = require('exceljs');
var excelData = require('./excelData').excelData;
const fs = require('fs');

/**
 * 判断文件是否被占用，防止后面写入的时候出错
 * @param {*} filePath 
 * @returns 
 */
async function isFileInUse(filePath) {
  return new Promise((resolve, reject) => {
    fs.open(filePath, 'r+', (err, fd) => {
      if (err) {
        if (err.code === 'EBUSY') {
          resolve(true); // File is locked
        } else {
          reject(err); // Other error occurred
        }
      } else {
        fs.close(fd, (err) => {
          if (err) {
            reject(err);
          } else {
            resolve(false); // File is not locked
          }
        });
      }
    });
  });
}
/**
 * 把包含richText的对象转换为字符串
 * @param {object} value 包含richText的对象
 */
function getValue(value) {
  if (!value) return '';
  const arr = value.richText;
  if (!arr) return '';
  let str = '';
  for (let i = 0; i < arr.length; i++) {
    str += arr[i].text;
  }
  return str;
}
/**
 * 读取./excel/bgd.xlsx文件
* @param {string} fileName 指定excel文件名，默认./excel/columns.xlsx
* @returns {ExcelData} 返回ExcelData对象
*/
async function readExcel(fileName = './excel/bgd.xlsx') {
  const isUsed = await isFileInUse(fileName);
  if (isUsed) throw new Error('文件被占用，请先关闭相关应用程序在试');
  const workbook = new Excel.Workbook();
  await workbook.xlsx.readFile(fileName);
  const sheet = workbook.worksheets[0];
  await excelData.getCompanyInfo(sheet.getRow(2));
  excelData.goodsList = [];
  for (let i = 4; i <= sheet.rowCount; i++) {
    excelData.addGoodsInfo(sheet.getRow(i), i);
  }
  return excelData;
}
/**
 * 写入./excel/bgd.xlsx文件
* @param {string} fileName 指定excel文件名，默认./excel/columns.xlsx
* @param {Array} data 要写入的数据，格式为[{rowIndex,title,url}]
*/
async function writeExcel(fileName = './excel/bgd.xlsx', data = [{ rowIndex, title, url }]) {

  const workbook = new Excel.Workbook();
  await workbook.xlsx.readFile(fileName);
  const sheet = workbook.worksheets[0];
  for (let i = 0; i < data.length; i++) {
    const goodsData = data[i];
    sheet.getRow(goodsData.rowIndex).getCell(5).value = goodsData.title;
    sheet.getRow(goodsData.rowIndex).getCell(6).value = goodsData.url;
  }
  await workbook.xlsx.writeFile(fileName)
}
module.exports =
{
  /**
   * 读取excel
   */
  readExcel,
  /**
   * 写入excel
   */
  writeExcel
};
/**
 * 测试用例
 */
// (async () => {
//   const res = await readExcel();
//   console.log(res);
// })();